#include "mainwidget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QMessageBox>
#include <QtSql/QSqlDatabase>
mainwidget::mainwidget(QWidget *parent)
    : QWidget{parent}
    , btn(new QPushButton("管理界面"))
    ,  insertBtn(new QPushButton("插入数据"))
{
    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->addWidget(btn);
    mainLayout->addWidget(insertBtn);
    setLayout(mainLayout);

    connect(btn,&QPushButton::clicked,this,&mainwidget::clickManager);
    connect(insertBtn,&QPushButton::clicked,this,&mainwidget::clickInsert);
    //QTableAttribute *ta = initData("D:\\gitcode.com\\QDynamicForm\\Data\\template.json");
    QTableAttribute *ta = initData("../../../../Data/template.json");
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("test.db");
    db.open();
    if(nullptr == ta){
        QMessageBox::information(this,"提示","template.json解析失败");
    }else{
        dynamicFrom = new QDynamicForm();
        if(!dynamicFrom->init(&db,ta)){
            qInfo()<<"初始化失败！";
        }
    }


}

void mainwidget::clickInsert()
{
    dynamicFrom->showInsertWidget();
}

QTableAttribute * mainwidget::initData(QString jsonPath)
{
    QTableAttribute *ta = new QTableAttribute;
    QFile file(jsonPath);
    if(!file.open(QIODevice::Text | QIODevice::ReadOnly)){
        return nullptr;
    }
    QJsonDocument doc =QJsonDocument::fromJson(file.readAll());
    if(doc.isNull() || doc.isEmpty()){
        return nullptr;
    }
    QJsonObject jobj = doc.object();
    QString tableName = jobj["name"].toString();
    QJsonArray jarr = jobj["FieldAttribute"].toArray();
    for(auto item :std::as_const(jarr)){
        QJsonObject itemObj=    item.toObject();
        QFieldAttribute fieldAttribute;
        fieldAttribute.fieldName = itemObj.find("name").value().toString();
        fieldAttribute.label = itemObj.find("label").value().toString();
        fieldAttribute.value = itemObj.find("value").value().toString();
        QString fieldType = itemObj.find("fieldType").value().toString();
        if(fieldType == "TEXT"){
            fieldAttribute.fieldType = QFieldAttribute::TEXT;
        }else if(fieldType == "COMBOBOX"){
            fieldAttribute.fieldType = QFieldAttribute::COMBOBOX;
        }else if(fieldType == "NUMBER"){
            fieldAttribute.fieldType = QFieldAttribute::BUMBER;
        }
        fieldAttribute.createSql = itemObj.find("createSql").value().toString();
        ta->fieldAttributes.push_back(fieldAttribute);
    }
    ta->tableName = tableName;
    qInfo()<< tableName;
    return ta;
}

void mainwidget::clickManager()
{
    dynamicFrom->showManagerWidget();
}
